package com.junmeng.lib.cascade.util

import com.junmeng.lib.cascade.SourceCascadePlugin
import com.junmeng.lib.cascade.bean.Config
import org.gradle.api.initialization.Settings
import java.io.File


object SourceCascadeUtil {
    fun startCascade(settings: Settings, config: Config) {
        if (!config.enableCascade) {
            return
        }
        if (config.cascadeModuleMap.isEmpty()) {
            return
        }
        config.cascadeModuleMap.forEach {
            addInclude(settings, it.key, it.value)
        }

        handleSubstitute(settings, config.cascadeModuleMap)
    }

    private fun addInclude(settings: Settings, module: String?, modulePath: String?) {
        if (module.isNullOrEmpty() || modulePath.isNullOrEmpty()) {
            Log.log("${SourceCascadePlugin.CONFIG_CASCADE_MODULE_MAP}的key或者value不能为空")
            return
        }

        val projectName = turnProjectName(module!!)
        val modulePath = File(modulePath)
        if (!modulePath.exists()) {
            Log.log("${module}对应的路径：${modulePath} 不存在，请仔细检查")
            return
        }
        Log.log("添加include:projectName=${projectName},modulePath=${modulePath}")

        settings.include(projectName)
        settings.project(":${projectName}").projectDir = modulePath
    }

    private fun handleSubstitute(settings: Settings, cascadeModuleMap: Map<String, String>) {
        settings.gradle.allprojects {
            if (it == it.rootProject) {
                return@allprojects
            }
            Log.log("project=$it")
            it.configurations.all {
                it.resolutionStrategy.dependencySubstitution {
                    //将项目中的依赖替换
                    cascadeModuleMap.forEach { entry ->
                        if (File(entry.value).exists()) {
                            it.substitute(it.module("${entry.key}"))
                                .using(it.project(":${turnProjectName(entry.key)}"))
                        }
                    }
                }
            }
        }
    }

    private fun turnProjectName(module: String): String {
        return module.replace(":", "_")
    }
}